<template>

  <div class="demo-form-top">
    <div class="demo-input-size">
      <label style="margin-right: 10px;">用户名称 </label>
      <el-input
          style="width: 200px"
          v-model="input1"
          class="w-50 m-2"
          size="large"
          placeholder="请输入用户名搜索"
          :suffix-icon="Search"
      />
    </div>
    <div class="demo-input-size">
      <label style="margin-right: 10px;">手机号 </label>
      <el-input
          style="width: 200px"
          v-model="input2"
          class="w-50 m-2"
          size="large"
          placeholder="请输入手机号搜索"
          :suffix-icon="Search"
      />
    </div>
    <div class="demo-input-size">
      <label style="margin-right: 10px;">状态 </label>
      <el-select v-model="selectStatus" placeholder="筛选状态"  size="large">
        <el-option :key="1" label="正常" :value="1"></el-option>
        <el-option :key="0" label="异常" :value="0"></el-option>
      </el-select>
    </div>
    <div class="demo-button-size">
      <el-button type="primary" @click="getUserList">搜索</el-button>
    </div>
    <div class="demo-button-size">
      <el-button type="success" @click="addOpen">新增</el-button>
    </div>
    <div class="demo-button-size">
      <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
        <template #reference>
          <el-button type="danger"  :disabled="delBtlStatu">批量删除</el-button>
        </template>
      </el-popconfirm>
    </div>
  </div>


  <div class="demo-table-size">
    <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        tooltip-effect="dark"
        stripe
        border
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"  />
      <el-table-column property="username" label="用户名" width="120" align="center" />
      <el-table-column property="headImg" label="用户头像" align="center">
        <template #default="scope">
          <el-image
              style="width: 60px; height: 60px"
              :src="baseUrl+scope.row.headImg"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column property="phone" label="手机号" align="center"  />
      <el-table-column property="age" label="年龄" align="center"  />
      <el-table-column property="email" label="邮箱" align="center"  />
      <el-table-column property="type" label="用户角色" align="center" >
        <template #default="scope">
          <el-tag class="ml-2" type="warning" v-if="scope.row.type == 0">用户</el-tag>
          <el-tag class="ml-2" type="danger" v-if="scope.row.type == 2">管理员</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="status" label="状态" align="center" >
        <template #default="scope">
          <el-tag class="ml-2" type="success" v-if="scope.row.status == 1">正常</el-tag>
          <el-tag class="ml-2" type="danger" v-if="scope.row.status == 0">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="address" label="地址" align="center" show-overflow-tooltip >
      </el-table-column>
      <el-table-column property="icon"  align="center" width="200" label="操作">
        <template #default="scope">
          <el-button type="primary"  @click="editHandle(scope.row.id)" >编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="这是一段内容确定删除吗？" @click="delHandle(scope.row.id)"     @confirm="">
            <template #reference>
              <el-button type="danger" >删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>

    </el-table>
    <div style="margin-top: 15px;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="float: right;margin-right: 30px"
          small
          background
          :page-sizes="[5, 10, 20, 30]"
          v-model:total="pageParam.total"
          layout="total, sizes, prev, pager, next"
          class="mt-4"
          v-model:current-page="pageParam.current"
          v-model:page-size="pageParam.size"
      />


    </div>
  </div>

  <!--新增对话框-->
  <el-dialog
      :title="dialogName"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose">

    <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="editForm"  >


      <el-form-item label="用户名" prop="username" label-width="80px">
        <el-input  v-model="editForm.username" ></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone" label-width="80px">
        <el-input  v-model="editForm.phone" ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email" label-width="80px">
        <el-input  v-model="editForm.email" ></el-input>
      </el-form-item>
      <el-form-item label="用户头像"  prop="headImg" label-width="100px">
        <UploadUtil  v-model="editForm.headImg" :message="parentMessage"  @childEvent="handleChildEvent" />
      </el-form-item>
      <el-form-item label="年龄"  prop="age" label-width="100px">
        <el-input-number v-model="editForm.age" :min="1" :max="100" />
      </el-form-item>
      <el-form-item label="角色"  prop="type" label-width="100px">
        <el-radio-group v-model="editForm.type" class="ml-4">
          <el-radio :label="0">用户</el-radio>
          <el-radio :label="2">管理员</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态"  prop="status" label-width="100px">
        <el-radio-group v-model="editForm.status" class="ml-4">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">异常</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="地址"  prop="address" label-width="100px">
        <el-input  v-model="editForm.address"  :autosize="{ minRows: 5, maxRows: 15}"  type="textarea"  autocomplete="off"></el-input>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm(ruleFormRef)">取 消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
    </div>
    <el-form-item  prop="id" >
      <el-input type="hidden" v-model="editForm.id" ></el-input>
    </el-form-item>
  </el-dialog>



</template>
<script setup>


import {Search} from "@element-plus/icons-vue";
import {inject, nextTick, onMounted, reactive, ref} from "vue";
import UploadUtil from "@/components/UploadUtil.vue";
import { ElMessage } from 'element-plus';
import axios from "@/axios.js"

const baseUrl = '../../public/img/'



const input1 = ref('')
const input2 = ref('')

onMounted(()=>{
  getUserList()
})

const pageParam = ref({
  current:1,
  total:10,
  size:5
})

const selectStatus = ref("")
//分页查询
const getUserList = ()=>{
  axios.get(`/user/list`,{
    params: {
      username: input1.value,
      phone:input2.value,
      status:selectStatus.value,
      current: pageParam.value.current,
      size: pageParam.value.size
    }
  }).then(res=>{
    tableData.value = res.data.records
    pageParam.value.current = res.data.current
    pageParam.value.total= res.data.total
    pageParam.value.size = res.data.size
  })
}

const handleSizeChange = (val)=>{
  console.log(`每页 ${val} 条`)
  pageParam.value.size = val
  getUserList()
}
const handleCurrentChange = (val)=>{
  console.log(`当前页: ${val}`)
  pageParam.value.current = val
  getUserList()
}


const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  console.log("勾选")
  console.log(val)
  multipleSelection.value = val
  delBtlStatu.value = val.length==0
}
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach(row => {
      multipleTableRef.value.toggleRowSelection(row)
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
}

const delBtlStatu = ref(true)

//删除/批量删除
const delHandle = (id) => {

  var ids = []
  if (id) {
    ids.push(id)
  } else {
    multipleSelection.value.forEach(row => {
      ids.push(row.id)
    })
  }
  console.log(ids)

  axios.post("/user/delete", ids).then(res => {
    ElMessage({
      showClose: true,
      message: '恭喜你，删除成功',
      type: 'success',
      onClose: () => {
        getUserList() // 在消息关闭时调用getBrandList方法
      }
    });
  })
}


const tableData = ref(
    [
      {
        id:1,
        username: 'Tom',
        headImg:"",
        phone:"",
        age:"",
        email:"",
        type:1,
        status:1,
        address:"",

      }
    ]
)

//图片上传部分
const handleChildEvent = (data) => {
  console.log('Received from child: ' + data);
  parentMessage.value = data
  editForm.value.headImg = parentMessage
};
const parentMessage = ref('');



//新增/编辑
const dialogVisible = ref(false)
const handleClose = ()=>{
  dialogVisible.value = false
  parentMessage.value= ""
  editForm.value = ref({})
}
const editForm = ref({


})


const ruleFormRef = ref(null)

const rules = reactive({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '手机不能为空', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱', trigger: ['blur', 'change'] },
  ],
  headImg: [
    { required: true, message: '用户头像不能为空', trigger: 'change' },
  ],
  age: [
    { required: true, message: '年龄不能为空', trigger: 'blur' },
    { type: 'number', message: '年龄必须为数字值', trigger: ['blur', 'change'] },
  ],
  type: [
    { required: true, message: '角色不能为空', trigger: 'change' },
  ],
  status: [
    { required: true, message: '状态不能为空', trigger: 'change' },
  ],
  address: [
    { required: true, message: '地址不能为空', trigger: 'blur' },
  ],
});
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(editForm.value)
      axios.post('/user/' + (editForm.value.id?'update':'save'), editForm.value)
          .then(res => {

            ElMessage({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
                getUserList() // 在消息关闭时调用getBrandList方法
              }
            });
            dialogVisible.value =false
            resetForm(formEl)
          })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const editHandle = (id) => {

  axios.get('/user/info/' + id).then(res => {
    editOpen()
    nextTick(() => {
      editForm.value = res.data
      parentMessage.value = editForm.value.headImg
    })

  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  dialogVisible.value = false
  parentMessage.value = ""
  formEl.resetFields()
}

const dialogName = ref("")

const addOpen = ()=>{
  dialogName.value = "新增"
  dialogVisible.value = true
}
const editOpen = ()=>{
  dialogName.value = "编辑"
  dialogVisible.value = true
}



</script>


<style scoped>
.demo-form-top{

}

.demo-button-size{
  float: left;
  display: flex;
  align-items: center;
  margin-top: 5px;
  margin-left: 7px;
}

.demo-input-size{
  float: left;
  width: 300px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.demo-table-size{

  margin-top: 20px;
}

.dialog-footer{
  margin-left: 100px;
}


</style>
<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-table__header thead th {
  background-color: #F5F7FA!important;
}

</style>